package com.jy.admin.services.cashPocket;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.jy.admin.db.dao.*;
import com.jy.admin.db.entity.*;
import com.jy.admin.enums.*;
import com.jy.admin.jobs.BaseJobHandler;
import com.jy.admin.services.BaseCrawlerService;
import com.jy.admin.services.cashPocket.vo.*;
import com.jy.bo.common.conf.util.HttpUtil;
import com.robert.vesta.util.IdUtils;
import okhttp3.*;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.imageio.stream.FileImageInputStream;
import java.io.*;
import java.math.BigDecimal;
import java.net.*;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2022/1/10
 * Time: 8:49 下午
 */
@Service
public class OkRupeeService extends BaseCrawlerService {
    private static final Logger LOGGER = LoggerFactory.getLogger(OkRupeeService.class);

    @Autowired
    private CeOrdersDetailDao ordersDetailDao;

    @Autowired
    private CeMerchantDao merchantDao;

    @Autowired
    private CeCommentPushLogDao commentPushLogDao;

    @Autowired
    private CeAgentAccountDao agentAccountDao;

    @Autowired
    private CeRepaymentLinkDao repaymentLinkDao;

    @PostConstruct
    public void init() {
        BaseJobHandler.merchantAndServiceMap.put("okrupee", this);
        BaseJobHandler.merchantAndServiceMap.put("cashmart", this);
    }

    public String manualLogin(String agentCode,String cookie) {
        if (StringUtils.isEmpty(cookie)){
            return "登录失败";
        }
        CeAgentAccountEntity agentAccount = agentAccountDao.getByAgentCode(agentCode);
        LOGGER.info("== tiger 登录接口 ==,cookie:{}", cookie);
        if (StringUtils.isNotEmpty(cookie)) {
            JSONObject requestHeader = new JSONObject();
            requestHeader.put("Cookie",cookie);
            requestHeader.put("Content-Type", "application/json");
            agentAccount.setRequestHeader(requestHeader.toString());
            agentAccount.setLoginDt(new Date());
            agentAccount.setLoginStatus(1);
            agentAccountDao.updateByPrimaryKey(agentAccount);
            return "登录成功";
        } else {
            LOGGER.info("== 请求登录接口 失败 ==");
            agentAccount.setLoginStatus(2);
            agentAccountDao.updateByPrimaryKey(agentAccount);
            return "登录失败";
        }
    }

    public boolean autoLogin(CeAgentAccountEntity agentAccount) {
        if (apolloConfigUtil.isAutoLoginOpen()) {
            CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
            String statusUrl = merchant.getApiDomain() + "/index.php?r=main/login";
            String params = "LoginForm[username]=" + agentAccount.getAccount() + "&LoginForm[password]=" + agentAccount.getPassword() + "&LoginForm[phoneCaptcha]=";
            Response response = HttpUtil.postOptions(statusUrl, params);
            if (response == null) {
                LOGGER.info("== 自动登录失败 ==");
                agentAccount.setLoginStatus(2);
                agentAccountDao.updateByPrimaryKey(agentAccount);
                return false;
            }
            Headers headers = response.priorResponse().priorResponse().headers();
            List<String> values = headers.values("Set-Cookie");
            String cookie = "";
            for (int i = 0; i < values.size(); i++) {
                String s = values.get(i);
                cookie += s.substring(0, s.indexOf(";") + 1) + " ";
            }
            if (cookie.length() > 2) {
                cookie = cookie.substring(0, cookie.length() - 2);
                LOGGER.info("获取的常规Cookie:===============,res:{},cookie:{}", values.toString(), cookie);
            }
            if (StringUtils.isNotEmpty(cookie)) {
                LOGGER.error("== 自动登录成功==，data:{}", cookie);
                JSONObject requestHeader = new JSONObject();
                requestHeader.put("Cookie", cookie);
                requestHeader.put("Content-Type", "application/json");
                agentAccount.setRequestHeader(requestHeader.toString());
                agentAccount.setLoginDt(new Date());
                agentAccount.setLoginStatus(1);
                agentAccountDao.updateByPrimaryKey(agentAccount);
                return true;
            } else {
                LOGGER.info("== 自动登录失败 ==");
                agentAccount.setLoginStatus(2);
                agentAccountDao.updateByPrimaryKey(agentAccount);
            }
        } else {
            LOGGER.info("== 未开启自动登录 ==");
            agentAccount.setLoginStatus(2);
            agentAccountDao.updateByPrimaryKey(agentAccount);
        }
        return false;
    }

    public String login(String agentCode, String code) {
        CeAgentAccountEntity agentAccount = agentAccountDao.getByAgentCode(agentCode);
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String statusUrl = merchant.getApiDomain() + "/index.php?r=main/login";
        String params = "LoginForm[username]=" + agentAccount.getAccount() + "&LoginForm[password]=" + agentAccount.getPassword() + "&LoginForm[phoneCaptcha]=" + code;
        Response response = HttpUtil.postOptions(statusUrl, params);
        if (response == null) {
            LOGGER.info("== 自动登录失败 ==");
            agentAccount.setLoginStatus(2);
            agentAccountDao.updateByPrimaryKey(agentAccount);
            return "登陆失败";
        }
        Headers headers = response.priorResponse().priorResponse().headers();
        List<String> values = headers.values("Set-Cookie");
        String cookie = "";
        for (int i = 0; i < values.size(); i++) {
            String s = values.get(i);
            cookie += s.substring(0, s.indexOf(";") + 1) + " ";
        }
        if (cookie.length() > 2) {
            cookie = cookie.substring(0, cookie.length() - 2);
            LOGGER.info("获取的常规Cookie:===============,res:{},cookie:{}", values.toString(), cookie);
        }
        if (StringUtils.isNotEmpty(cookie)) {
            LOGGER.error("== 自动登录成功==，data:{}", cookie);
            JSONObject requestHeader = new JSONObject();
            requestHeader.put("Cookie", cookie);
            requestHeader.put("Content-Type", "application/json");
            agentAccount.setRequestHeader(requestHeader.toString());
            agentAccount.setLoginDt(new Date());
            agentAccount.setLoginStatus(1);
            agentAccountDao.updateByPrimaryKey(agentAccount);
            return "登陆成功";
        } else {
            LOGGER.info("== 自动登录失败 ==");
            agentAccount.setLoginStatus(2);
            agentAccountDao.updateByPrimaryKey(agentAccount);
        }
        return "登陆失败";
    }


    @Override
    public boolean hasLogin(CeAgentAccountEntity agentAccount) {
        if (apolloConfigUtil.isLoginStatusUseCache()) {
            return agentAccount.getLoginStatus() == 1;
        }

        if (agentAccount.getLoginStatus() == 2) {
            LOGGER.error("== 账号 token不可用 ==,account:{}", agentAccount.getAccount());
            boolean isLogin = autoLogin(agentAccount);
            if (!isLogin) {
                return false;
            }
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String url = merchant.getApiDomain() + "/index.php?r=main/welcome";
        LOGGER.info("== 检测登陆 开始请求订单列表 ==,url:{}", url);

        Map<String, String> headers = getHeaders(agentAccount);
        Map<String, String> params = Maps.newHashMap();
        String result = HttpUtil.getPage(url, params, headers);
        if (StringUtils.isEmpty(result)) {
            LOGGER.error("== 请求接口数据出错 当前账号token无效==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
            return autoLogin(agentAccount);
        }
        try {
            if (result.contains("Absent to Go Home") || result.contains("催收后台登陆")) {
                LOGGER.error("== 请求接口数据出错 当前账号token无效==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
                return autoLogin(agentAccount);
            }

        } catch (Exception e) {
            LOGGER.error("== 请求接口数据出错 当前账号登陆异常==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType(), e);
        }

        return true;
    }

    @Override
    public void refresh(CeAgentAccountEntity agentAccount) {

        updateOrderList(agentAccount);
        updateOrderDetailInfo(agentAccount);
    }

    @Override
    public void updateOrderList(CeAgentAccountEntity agentAccount) {
        if (agentAccount.getStage().contains("admin")) {
            return;
        }
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());

        int perPage = 15;
        List<OkRupeeTableElement> items = new ArrayList<>();
        Elements trs;
        for (int z = 1; z <= 20; z++) {
            String url = merchant.getApiDomain() + "/index.php?r=work-desk/admin-in-collection-order-list&page=" + z + "&per-page=" + perPage;
            LOGGER.info("== 开始请求订单列表 ==,url:{}", url);
            Map<String, String> headers = getHeaders(agentAccount);
            Map<String, String> params = Maps.newHashMap();
            String result = HttpUtil.getPage(url, params, headers);

            Document document = Jsoup.parse(result);
            trs = document.select("table").select("tr");

            for (int i = 1; i < trs.size(); i++) {
                OkRupeeTableElement element = new OkRupeeTableElement();
                Elements tds = trs.get(i).select("td");

                for (int j = 0; j < tds.size(); j++) {
                    if (tds.get(j).childNodes().size() <= 0) {
                        continue;
                    }
                    String value = tds.get(j).childNodes().get(0).toString();
                    if (value.contains(",")) {
                        value = value.replace(",", "");
                    }
                    if (j == 1) {
                        value = tds.get(j).childNodes().get(0).childNode(0).toString();
                        element.setId(value);
                    } else if (j == 2) {
                        value = tds.get(j).childNodes().get(0).childNode(0).toString();
                        element.setOrderNumber(value);
                    } else if (j == 4) {
                        element.setAppName(value);
                    } else if (j == 5) {
                        element.setProductName(value);
                    } else if (j == 6) {
                        element.setName(value);
                    } else if (j == 7) {
                        element.setIsReloan(value.contains("old") ? "2" : "1");
                    } else if (j == 9) {
                        element.setPhoneNumber(value);
                    } else if (j == 10) {
                        element.setTotalLoanAmount(value);
                    } else if (j == 12) {
                        element.setRepaymentAmount(value);
                    } else if (j == 13) {
                        element.setRemainingAmount(value);
                    } else if (j == 14) {
                        Date date = DateUtil.getDate(value, "dd-MM-yyyy");
                        String date1 = DateUtil.getDate(date, "yyyy-MM-dd");
                        element.setRepaymentDate(date1);
                    } else if (j == 15) {
                        element.setOverdueDays(value);
                    } else if (j == 16) {
                        element.setLateFee(value);
                    } else if (j == 17) {
                        element.setPaidAmount(value);
                    } else if (j == 18) {
                        if (value.contains("--")) {
                            value = value.replace("--", "");
                        } else {
                            Date date = DateUtil.getDate(value, "dd-MM-yyyy");
                            value = DateUtil.getDate(date, "yyyy-MM-dd");
                        }
                        element.setPaidDate(value);
                    } else if (j == 20) {
                        element.setCollectionResult(value);
                    }

                }
                if (StringUtils.isNotEmpty(element.getId()) && StringUtils.isNotEmpty(element.getOrderNumber()) && !element.getRemainingAmount().equals("0")) {
                    items.add(element);
                }
            }
            if (trs.size() <= perPage) {
                break;
            }
        }

        if (items.size() == 0) {
            LOGGER.info("== 当前没有订单 ==");
            return;
        }

        //查询今天该账号的所有有效订单
        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());


        //如果为空则全部选择插入，这个其实就是初始化数据
        if (CollectionUtils.isEmpty(activeOrders)) {
            LOGGER.info("==当天没有数活跃数据 开始插入新数据 ==，size:{}", items.size());
            items.forEach(item -> {
                try {
                    String orderNo = item.getOrderNumber();
                    CeOrdersEntity oneByOrderNoAndAgentCode = ordersDao.getTodayOneByOrderNoAndAgentCode(orderNo, agentAccount.getAgentCode());
                    String collectionNo = IdUtils.genId() + "";
                    if (oneByOrderNoAndAgentCode == null) {
                        CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                                .setAgentCode(agentAccount.getAgentCode())
                                .setMerchantCode(agentAccount.getMerchantCode())
                                .setOrderNo(item.getOrderNumber())
                                .setOrderInfo(JsonStream.serialize(item))
                                .setStatus(OrderStatusEnum.active.getStatus())
                                .setCreateDt(new Date())
                                .setCollectionNo(collectionNo);
                        ordersDao.insert(ceOrdersEntity);
                    }

                } catch (Exception e) {
                    LOGGER.error("== 插入数据发生异常 ==,account:{},loanId:{}", agentAccount.getAccount(), item.getOrderNumber(), e);
                }
            });

        } else {
            //更新数据
            items.forEach(item -> {
                try {
                    String orderNo = item.getOrderNumber();
                    String collectionNo = IdUtils.genId() + "";
                    CeOrdersEntity OneByOrderNo = ordersDao.getTodayOneByOrderNoAndAgentCode(orderNo, agentAccount.getAgentCode());
                    if (OneByOrderNo == null) {
                        LOGGER.info("== 列表为空,插入订单 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), orderNo);
                        CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                                .setAgentCode(agentAccount.getAgentCode())
                                .setMerchantCode(agentAccount.getMerchantCode())
                                .setOrderNo(orderNo)
                                .setOrderInfo(JsonStream.serialize(item))
                                .setStatus(OrderStatusEnum.active.getStatus())
                                .setCreateDt(new Date())
                                .setCollectionNo(collectionNo);
                        ordersDao.insert(ceOrdersEntity);
                    } else {
                        LOGGER.info("== 订单已存在 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), orderNo);
                    }
                } catch (Exception e) {
                    LOGGER.error("== 插入数据发生异常 ==,account:{},orderNo:{}", agentAccount.getAccount(), item.getOrderNumber(), e);
                }
            });

            activeOrders.forEach(item -> {
                try {
                    String id = item.getOrderNo();
                    boolean hasOrder = false;
                    for (int i = 0; i < items.size(); i++) {
                        OkRupeeTableElement rupeeTableElement = items.get(i);
                        String orderNo = rupeeTableElement.getOrderNumber();
                        if (id.equals(orderNo)) {
                            LOGGER.info("== 当前订单存在 ==,account:{},orderNo:{}", agentAccount.getAccount(), orderNo);
                            hasOrder = true;
                            break;
                        }

                    }
                    if (!hasOrder) {
                        LOGGER.info("== 当前订单不存在 ==,account:{},orderNo:{}", agentAccount.getAccount(), id);
                        if (item.getStatus().equals(OrderStatusEnum.active.getStatus())) {
                            item.setStatus(OrderStatusEnum.updated.getStatus());
                            ordersDao.updateByPrimaryKey(item);
                        }
                    }
                } catch (Exception e) {
                    LOGGER.error("== 更新数据发生异常 ==,account:{},orderNo:{}", agentAccount.getAccount(), JsonIterator.deserialize(item.getOrderInfo()).get("id").toString(), e);
                }
            });

        }

        LOGGER.info("== 订单刷新处理完成 ==");

    }

    @Override
    public void updateOrderDetailInfo(CeAgentAccountEntity agentAccount) {
        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());
        if (CollectionUtils.isEmpty(activeOrders)) {
            return;
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());

        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        Map<String, String> params = Maps.newHashMap();

        activeOrders.forEach(order -> {

            try {
                boolean hasDetailData = order.getDetailStatus() == 1;

                Any orderInfoJson = JsonIterator.deserialize(order.getOrderInfo());
                String orderId = orderInfoJson.get("id").toString();


                Map<String, String> infoMap = new HashMap<>();
                String detailUrl = merchant.getApiDomain() + "/index.php?r=work-desk/collection-detail&order_id=" + orderId;
                String detailInfo = HttpUtil.getPage(detailUrl, params, headers);

                Document document = Jsoup.parse(detailInfo);
                Elements tables = document.select("table");
                int position;
                if (agentAccount.getStage().contains("s")) {
                    if (tables.size() > 6) {
                        position = 4;
                    } else {
                        position = 3;
                    }
                } else {
                    if (tables.size() >= 5) {
                        position = 3;
                    } else {
                        position = 2;
                    }
                }

                Elements repaymentTrs = tables.get(position).select("tr");
                JSONObject repaymentData = new JSONObject();
                for (int i = 1; i < repaymentTrs.size(); i++) {
                    Elements tds = repaymentTrs.get(i).select("td");
                    for (int j = 0; j < tds.size(); j++) {
                        if (tds.get(j).childNodes().size() <= 0) {
                            continue;
                        }
                        String value = tds.get(j).childNodes().get(0).toString();
                        if (value.equals("--")) {
                            continue;
                        }
                        if (value.contains(".")) {
                            value = value.replace(".", "");
                        }
                        if (value.contains(",")) {
                            value = value.replace(",", "");
                        }
                        if (j == 0) {
                            repaymentData.put("orderNumber", value);
                        } else if (j == 1) {
                            repaymentData.put("appName", value);
                        } else if (j == 2) {
                            repaymentData.put("productName", value);
                        } else if (j == 3) {
                            repaymentData.put("borrowCapital", value);
                        } else if (j == 4) {
                            repaymentData.put("borrowDate", value);
                        } else if (j == 5) {
                            repaymentData.put("repaymentAmount", value);
                        } else if (j == 6) {
                            repaymentData.put("remainAmount", value);
                        } else if (j == 7) {
                            repaymentData.put("repaymentDate", value);
                        } else if (j == 8) {
                            repaymentData.put("overdueDays", value);
                        } else if (j == 9) {
                            repaymentData.put("paidAmount", value);
                        } else if (j == 10) {
                            repaymentData.put("collectResults", value);
                        } else if (j == 11) {
                            Elements a = tds.get(j).select("a");
                            String appLink = a.get(0).attributes().get("data-clipboard-text");
                            repaymentData.put("appLink", appLink);
                        }


                    }

                    LOGGER.info("== adaf ==");
                }
                infoMap.put("repaymentInfo", repaymentData.toString());
                if (!repaymentData.get("remainAmount").toString().equals("0")) {
                    updateRemainMoney(order.getCollectionNo(), repaymentData.get("remainAmount").toString());
                }
                LOGGER.info("== 获取成功 repaymentInfo==");

//                Elements imgsNew = document.select("img");
//                JSONArray imagesNew = new JSONArray();
//                for (int i = 0; i < imgsNew.size(); i++) {
//                    String value = imgsNew.get(i).attributes().get("src");
//                    imagesNew.add(value);
//                }
//                infoMap.put("images", imagesNew.toString());
//                LOGGER.info("== 获取成功 baseInfo==,images:{}", imagesNew.toString());
//
//                ordersDao.updateImages(order.getOrderNo(), JsonStream.serialize(imagesNew), order.getMerchantCode());

                if (!hasDetailData) {
                    CeOrdersDetailEntity baseInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(merchant.getMerchantCode(), "baseInfo", order.getOrderNo());
                    if (baseInfoDetail == null) {
                        JSONObject basicData = new JSONObject();
                        Elements baseTrs = tables.get(0).select("tr");
                        for (int i = 1; i < baseTrs.size(); i++) {
                            Elements tds = baseTrs.get(i).select("td");
                            for (int j = 0; j < tds.size(); j++) {
                                if (tds.get(j).childNodes().size() <= 0) {
                                    continue;
                                }
                                String value = tds.get(j).childNodes().get(0).toString();
                                if (j == 0) {
                                    value = tds.get(j).childNodes().get(0).childNode(0).toString();
                                    basicData.put("name", value);
                                } else if (j == 1) {
                                    value = tds.get(j).childNodes().get(0).childNode(0).toString();
                                    basicData.put("email", value);
                                } else if (j == 2) {
                                    String phone = tds.get(j).childNodes().get(0).attributes().get("_phone");
                                    String href = tds.get(j).childNodes().get(0).attributes().get("href");
                                    href = href.substring(href.indexOf(",") + 1);
                                    basicData.put("callId", href);
                                    basicData.put("phone", phone);
                                } else if (j == 3) {
                                    basicData.put("isReloan", value);
                                }

                            }
                        }

                        if (agentAccount.getStage().contains("s")) {
                            Elements addressTrs = tables.get(5).select("tr");
                            for (int i = 1; i < addressTrs.size(); i++) {
                                Elements tds = addressTrs.get(i).select("td");
                                for (int j = 0; j < tds.size(); j++) {
                                    if (tds.get(j).childNodes().size() <= 0) {
                                        continue;
                                    }
                                    String value = tds.get(j).childNodes().get(0).toString();
                                    if (j == 4) {
                                        basicData.put("address", value);
                                    }

                                }
                            }
                        }


                        LOGGER.info("== 获取成功 baseInfo==,basicData:{}", basicData.toString());
                        infoMap.put("baseInfo", basicData.toString());
                    } else {
                        baseInfoDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(baseInfoDetail);
                    }

//                    CeOrdersDetailEntity imagesDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(merchant.getMerchantCode(), "images", order.getOrderNo());
//                    if (imagesDetail == null) {
                    Elements imgs = document.select("img");
                    JSONArray images = new JSONArray();
                    for (int i = 0; i < imgs.size(); i++) {
                        String value = imgs.get(i).attributes().get("src");
                        images.add(value);
                    }
                    infoMap.put("images", images.toString());
                    LOGGER.info("== 获取成功 baseInfo==,images:{}", images.toString());

//                    } else {
//                        imagesDetail.setGmtModified(new Date());
//                        ordersDetailDao.updateByPrimaryKey(imagesDetail);
//                    }

                    CeOrdersDetailEntity contactInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(merchant.getMerchantCode(), "contactInfo", order.getOrderNo());
                    if (contactInfoDetail == null) {
                        JSONArray contactData = new JSONArray();
                        Elements baseTrs = tables.get(1).select("tr");
                        for (int i = 1; i < baseTrs.size(); i++) {
                            Elements tds = baseTrs.get(i).select("td");
                            JSONObject contact = new JSONObject();
                            for (int j = 0; j < tds.size(); j++) {
                                if (tds.get(j).childNodes().size() <= 0) {
                                    continue;
                                }
                                if (j == 0) {
                                    String value = tds.get(j).childNodes().get(0).toString();
                                    contact.put("name", value.trim().equals("") ? "no" : value);
                                } else if (j == 2) {
                                    List<Node> nodes = tds.get(j).childNodes();
                                    for (int k = 0; k < nodes.size(); k++) {
                                        String s = nodes.get(k).toString();
                                        if (StringUtils.isNotEmpty(s)) {
                                            Document doc = Jsoup.parse(s);
                                            Elements childTrs = doc.select("a");
                                            if (childTrs.size() > 0) {
                                                String phone = childTrs.get(0).attributes().get("_phone");
                                                if (!phone.equals("")) {
                                                    contact.put("phone", phone);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (contact.size() > 0) {
                                contactData.add(contact);
                            }
                        }
                        LOGGER.info("== 获取成功 contactInfoDetail ==,contactData:{}", contactData);
                        infoMap.put("contactInfo", contactData.toString());
                    } else {
                        contactInfoDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(contactInfoDetail);
                    }

                    CeOrdersDetailEntity contactUrlDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(merchant.getMerchantCode(), "contactUrl", order.getOrderNo());
                    if (contactUrlDetail == null) {
                        LOGGER.info("== 获取成功 addressBook==");
                        try {
                            JSONArray contactData = new JSONArray();
                            Elements baseTrs = tables.get(2).select("tr");
                            for (int i = 1; i < baseTrs.size(); i++) {
                                Elements tds = baseTrs.get(i).select("td");
                                JSONObject contact = new JSONObject();
                                for (int j = 0; j < tds.size(); j++) {
                                    if (tds.get(j).childNodes().size() <= 0) {
                                        continue;
                                    }
                                    if (j == 0) {
                                        String value = tds.get(j).childNodes().get(0).toString();
                                        contact.put("name", value);
                                    } else if (j == 1) {
                                        List<Node> nodes = tds.get(j).childNodes();
                                        for (int k = 0; k < nodes.size(); k++) {
                                            String s = nodes.get(k).toString();
                                            if (StringUtils.isNotEmpty(s)) {
                                                Document doc = Jsoup.parse(s);
                                                Elements childTrs = doc.select("a");
                                                if (childTrs.size() > 0) {
                                                    String phone = childTrs.get(0).attributes().get("_phone").trim();
                                                    if (!phone.equals("")) {
                                                        contact.put("phone", phone);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                if (contact.size() > 0 && contact.get("phone") != null) {
                                    contactData.add(contact);
                                }
                            }
                            JSONObject jsonData = new JSONObject();
                            jsonData.put("contacts", contactData);

                            String contactUrl = uploadContact(order.getOrderNo(), jsonData.toString());
                            LOGGER.info("== 上传通讯录，得到地址 ==,url:{}", contactUrl);
                            infoMap.put("contactUrl", contactUrl);
                        } catch (Exception e) {
                            LOGGER.error("== 通讯录转换错误 ==", e);
                        }
                    } else {
                        contactUrlDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(contactUrlDetail);
                    }

                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        if (byKeyAndMerchantAndOrderNo == null) {
                            CeOrdersDetailEntity ordersDetailEntity = new CeOrdersDetailEntity()
                                    .setOrderNo(order.getOrderNo())
                                    .setMerchantCode(order.getMerchantCode())
                                    .setDataKey(k)
                                    .setDetailInfo(infoMap.get(k));
                            ordersDetailDao.insert(ordersDetailEntity);
                        } else {
                            byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                            ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                        }

                    });

                    order.setSyncStatus(OrderSyncStatusEnum.waiting.getStatus());
                } else {
                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                        ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                    });
                }

                order.setDetailStatus(1);
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 程序处理有异常 ==", e);
                order.setDetailStatus(2);
                ordersDao.updateByPrimaryKey(order);
            }
        });

        LOGGER.info("== 程序处理完成 ==");
    }

    @Override
    public void compostCollectionData(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== compostCollectionData ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== compostCollectionData  没有需要同步的订单 ==，agentCode:{},syncStatus:{}", agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
            return;
        }

        LOGGER.info("== compostCollectionData  需要同步的订单 ==，size:{},account:{}", todayListBySyncStatusAndAgent.size(), agentAccount.getAccount());

        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                LOGGER.info("== 构建推送信息 基础信息 开始==,collectionNo:{},syncStatus:{}", order.getCollectionNo(), order.getSyncStatus());
                Any orderDetail = JsonIterator.deserialize(order.getOrderInfo());
                String appName = orderDetail.get("appName").toString().equals("null") ? orderDetail.get("productName").toString() : orderDetail.get("appName").toString() + "[" + orderDetail.get("productName").toString() + "]";
                ClOrderReceiveRequest request = new ClOrderReceiveRequest()
                        .setOrderBillNo(order.getCollectionNo())
                        .setTradeNo(order.getCollectionNo())
                        .setProductType(appName)
                        .setAppName(appName)
                        .setOriginOrderNo(order.getOrderNo())
                        .setProductCode(appName)
                        .setAccount(order.getAgentCode())
                        .setAccount_id(agentAccount.getId())
                        .setClientCode(order.getMerchantCode())
                        .setUserCode(IdUtils.genId() + "");

                CeOrdersDetailEntity contactInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactInfo", order.getOrderNo());
                Any contactInfoJson = JsonIterator.deserialize(contactInfo.getDetailInfo());

                CeOrdersDetailEntity baseInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "baseInfo", order.getOrderNo());
                Any baseInfoJson = JsonIterator.deserialize(baseInfo.getDetailInfo());

                CeOrdersDetailEntity repaymentInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                Any repaymentInfoJson = JsonIterator.deserialize(repaymentInfo.getDetailInfo());

                CeOrdersDetailEntity contactUrl = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());
                Any contactUrlJson = JsonIterator.deserialize(contactUrl.getDetailInfo());

                CeOrdersDetailEntity images = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "images", order.getOrderNo());
                Any imagesJson = JsonIterator.deserialize(images.getDetailInfo());

                String borrowCapital = repaymentInfoJson.get("borrowCapital").toString();
                String overdueDays = repaymentInfoJson.get("overdueDays").toString();
                String lateFee = orderDetail.get("lateFee").toString();
                Any isReloan = orderDetail.get("isReloan");

                String overdueRatio = "0";
                String serviceFee = "0";
                LOGGER.info("== 构建推送信息 计算逾期罚息利率 开始==,borrowCapital:{}，overdueDays:{}.lateFee:{}", borrowCapital, overdueDays, lateFee);
                if (!overdueDays.equals("0")) {
                    overdueRatio = new BigDecimal(lateFee).divide(new BigDecimal(overdueDays), 2, BigDecimal.ROUND_HALF_UP).divide(new BigDecimal(borrowCapital), 4, BigDecimal.ROUND_HALF_UP).toString();
                }

                LOGGER.info("== 构建推送信息 订单信息 开始==,collectionNo:{}", order.getCollectionNo());
                String paidAmount = repaymentInfoJson.get("paidAmount").toString();
                ClOrderInputVo orderInputVo = new ClOrderInputVo()
                        .setBorrowType(isReloan.toInt())
                        .setBorrowCapital(borrowCapital)
                        .setAppLink(repaymentInfoJson.get("appLink").toString())
                        .setChannel(appName)
                        .setCapitalCode(appName)
                        .setInterest("0")
                        .setDeductAmount("0")
                        .setLateFeeRatio(overdueRatio)
                        .setServiceFee(serviceFee)
                        .setLateServiceFee("0")
                        .setReceivedCapital(borrowCapital)
                        .setPaidAmount(paidAmount)
                        .setReceivedDate(repaymentInfoJson.get("borrowDate").toString())
                        .setRepaymentDate(repaymentInfoJson.get("repaymentDate").toString())
                        .setRemainMoney(repaymentInfoJson.get("remainAmount").toString())
                        .setTotalMoney(repaymentInfoJson.get("repaymentAmount").toString());

                request.setOrderInfo(orderInputVo);

                LOGGER.info("== 构建推送信息 个人信息 开始==,collectionNo:{}", order.getCollectionNo());

                String aadhaarNo = "no-data";
                String pancardNo = "no-data";
                String email = baseInfoJson.get("email").toString();

                String companyCity = "no-data";
                String companyProvince = "no-data";
                String friendName = "no";
                String friendMobile = "no";

                String parentName = "no";
                String parentPhone = "no";

                List<Any> anies = contactInfoJson.asList();
                String personMobile = baseInfoJson.get("phone").toString();
                String personName = baseInfoJson.get("name").toString();
                if (anies.size() >= 2) {
                    parentName = contactInfoJson.get(0).get("name").toString();
                    parentPhone = contactInfoJson.get(0).get("phone").toString();
                    friendName = contactInfoJson.get(contactInfoJson.size() - 1).get("name").toString();
                    friendMobile = contactInfoJson.get(contactInfoJson.size() - 1).get("phone").toString();
                }

                List<String> imagesList = new ArrayList<>();
                imagesJson.asList().forEach(v -> {
                    imagesList.add(v.toString());
                });

                ClUserInfoInputVo userInfoInputVo = new ClUserInfoInputVo()
                        .setUserLanguage("")
                        .setAadhaarNo(aadhaarNo)
                        .setPanCardNo(pancardNo)
                        .setAddress(baseInfoJson.get("address").toString())
                        .setBirthday(DateUtil.getDate("yyyy-MM-dd"))
                        .setCity(companyCity)
                        .setEmail(email)

                        .setContact1Mobile(parentPhone)
                        .setContact1Name(parentName)
                        .setContact1Relative(1)

                        .setContact2Mobile(friendMobile)
                        .setContact2Name(friendName)
                        .setContact2Relative(6)

                        .setEducation(0)
                        .setKycNo(aadhaarNo)
                        .setMobile(personMobile)

                        .setMarriedStatus(0)
                        .setName(personName)
                        .setPinCode("no")
                        .setState(companyProvince)
                        .setImages(imagesList)
                        .setSex(0)
                        .setContactUrl(contactUrlJson.toString());

                request.setUserInfo(userInfoInputVo);

                LOGGER.info("== 构建推送信息 完成==,collectionNo:{}", order.getCollectionNo());

                CePushLogEntity pushLogEntity = pushLogDao.selectByCollectionNo(order.getCollectionNo());
                if (pushLogEntity == null) {
                    pushLogEntity = new CePushLogEntity()
                            .setCollectionNo(order.getCollectionNo())
                            .setDetailInfo(JsonStream.serialize(request))
                            .setStatus(1);
                    pushLogDao.insert(pushLogEntity);
                } else {
                    pushLogEntity.setDetailInfo(JsonStream.serialize(request));
                    pushLogDao.updateByPrimaryKey(pushLogEntity);
                }


                LOGGER.info("== 构建推送信息 保存信息完成==,collectionNo:{}", order.getCollectionNo());
                order.setSyncStatus(OrderSyncStatusEnum.data_ready.getStatus());
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 构建推送信息 发生异常==,collectionNo:{}", order.getCollectionNo(), e);
                order.setSyncStatus(OrderSyncStatusEnum.data_fail.getStatus());
                ordersDao.updateByPrimaryKey(order);
            }
        });

    }

    @Override
    public void pushDataToCollection(CeAgentAccountEntity agentAccount) {
        super.pushDataToCollection(agentAccount);
    }

    @Override
    public void checkOrdersPaidStatus(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 检查订单支付情况 ==");
        List<CeOrdersEntity> waitingPaidCheckOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.updated.getStatus());
        if (CollectionUtils.isEmpty(waitingPaidCheckOrders)) {
            LOGGER.info("== 检查订单支付情况 没有状态更新的订单==,size:{}", waitingPaidCheckOrders.size());
            return;
        }

        LOGGER.info("== 检查订单支付情况==,size:{}", waitingPaidCheckOrders.size());
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));
        Map<String, String> params = Maps.newHashMap();
        List<OkRupeeTableElement> items = new ArrayList<>();
        if (!agentAccount.getStage().equals("s3")) {
            int perPage = 15;
            for (int z = 1; z <= 10; z++) {
                //获取已还款列表
                String repayUrl = merchant.getApiDomain() + "/index.php?r=work-desk/admin-success-collection-order-list&sort_type=desc&s_plan_fee_time=" + DateUtil.getConverseDay(DateUtil.getDate("yyyy-MM-dd"), 8) + "+00:00:00&e_plan_fee_time=" + DateUtil.getAfterSelectDay("yyyy-MM-dd", 2) + "+23:59:59&page=" + z + "&per-page=" + perPage + "&search_submit=filtering";
                String result = HttpUtil.getPage(repayUrl, params, headers);

                Document document = Jsoup.parse(result);
                Elements repayTrs = document.select("table").select("tr");

                for (int i = 1; i < repayTrs.size(); i++) {
                    OkRupeeTableElement element = new OkRupeeTableElement();
                    Elements tds = repayTrs.get(i).select("td");

                    for (int j = 0; j < tds.size(); j++) {
                        if (tds.get(j).childNodes().size() <= 0) {
                            continue;
                        }
                        String value = tds.get(j).childNodes().get(0).toString();
                        if (value.contains(",")) {
                            value = value.replace(",", "");
                        }
                        if (j == 1) {
                            element.setId(value);
                        } else if (j == 2) {
                            element.setOrderNumber(value);
                        } else if (j == 4) {
                            element.setAppName(value);
                        } else if (j == 5) {
                            element.setProductName(value);
                        } else if (j == 6) {
                            element.setName(value);
                        } else if (j == 7) {
                            element.setPhoneNumber(value);
                        } else if (j == 8) {
                            element.setIsReloan(value.contains("old") ? "2" : "1");
                        } else if (j == 10) {
                            element.setTotalLoanAmount(value);
                        } else if (j == 12) {
                            element.setRepaymentAmount(value);
                        } else if (j == 13) {
                            element.setRemainingAmount(value);
                        } else if (j == 14) {
                            Date date = DateUtil.getDate(value, "dd-MM-yyyy");
                            String date1 = DateUtil.getDate(date, "yyyy-MM-dd");
                            element.setRepaymentDate(date1);
                        } else if (j == 15) {
                            element.setOverdueDays(value);
                        } else if (j == 16) {
                            element.setLateFee(value);
                        } else if (j == 17) {
                            element.setPaidAmount(value);
                        } else if (j == 18) {
                            Date date = DateUtil.getDate(value, "dd-MM-yyyy");
                            value = DateUtil.getDate(date, "yyyy-MM-dd");
                            element.setPaidDate(value);
                        } else if (j == 20) {
                            element.setCollectionResult(value);
                        }

                    }

                    if (!element.getPaidDate().equals("")) {
                        LOGGER.info("== 已还款列表 ==,date:{}", element.getPaidDate());
                        if (StringUtils.isNotEmpty(element.getId()) && StringUtils.isNotEmpty(element.getOrderNumber()) && element.getPaidDate().equals(DateUtil.getDate("yyyy-MM-dd"))) {
                            items.add(element);
                        }
                    }
                }
                if (repayTrs.size() < perPage + 1) {
                    break;
                }
            }
        }

        waitingPaidCheckOrders.forEach(order -> {
            if (!agentAccount.getStage().equals("s3")) {
                LOGGER.info("== 已还款订单列表 ==,historyResultsList:{}", JsonStream.serialize(items));
                boolean isRepay = false;
                OkRupeeTableElement okRupeeTableElement = null;
                String successLoanAppId = order.getOrderNo();
                for (int i = 0; i < items.size(); i++) {
                    String loanAppId = items.get(i).getOrderNumber();
                    if (loanAppId.equals(successLoanAppId)) {
                        isRepay = true;
                        okRupeeTableElement = items.get(i);
                        break;
                    }
                }
                if (isRepay) {
                    LOGGER.info("== 订单已还款 ==,OrderNo:{}", order.getOrderNo());
                    if (okRupeeTableElement != null) {
                        order.setOrderInfo(JsonStream.serialize(okRupeeTableElement));
                    }
                    order.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
                    order.setStatus(OrderStatusEnum.paid_update.getStatus());
                    ordersDao.updateByPrimaryKey(order);
                    return;
                }
                LOGGER.info("== 订单未还款，移除订单 ==,orderNo:{}", order.getOrderNo());
                order.setStatus(OrderStatusEnum.removed.getStatus());
                order.setSyncStatus(OrderSyncStatusEnum.need_remove.getStatus());
                ordersDao.updateByPrimaryKey(order);
            } else {
                try {
                    Any orderDetail = JsonIterator.deserialize(order.getOrderInfo());
                    //获取已还款列表
                    String detailUrl = merchant.getApiDomain() + "/index.php?r=work-desk/collection-detail&order_id=" + orderDetail.get("id").toString();
                    String detailInfo = HttpUtil.getPage(detailUrl, params, headers);

                    Document document = Jsoup.parse(detailInfo);
                    Elements tables = document.select("table");
                    int position;
                    if (tables.size() > 6) {
                        position = 4;
                    } else {
                        position = 3;
                    }
                    Elements repaymentTrs = tables.get(position).select("tr");
                    JSONObject repaymentData = new JSONObject();
                    for (int i = 1; i < repaymentTrs.size(); i++) {
                        Elements tds = repaymentTrs.get(i).select("td");
                        for (int j = 0; j < tds.size(); j++) {
                            if (tds.get(j).childNodes().size() <= 0) {
                                continue;
                            }
                            String value = tds.get(j).childNodes().get(0).toString();
                            if (value.contains(".")) {
                                value = value.replace(".", "");
                            }
                            if (value.contains(",")) {
                                value = value.replace(",", "");
                            }
                            if (j == 0) {
                                repaymentData.put("orderNumber", value);
                            } else if (j == 1) {
                                repaymentData.put("appName", value);
                            } else if (j == 2) {
                                repaymentData.put("productName", value);
                            } else if (j == 3) {
                                repaymentData.put("borrowCapital", value);
                            } else if (j == 4) {
                                repaymentData.put("borrowDate", value);
                            } else if (j == 5) {
                                repaymentData.put("repaymentAmount", value);
                            } else if (j == 6) {
                                repaymentData.put("remainAmount", value);
                            } else if (j == 7) {
                                repaymentData.put("repaymentDate", value);
                            } else if (j == 8) {
                                repaymentData.put("overdueDays", value);
                            } else if (j == 9) {
                                repaymentData.put("paidAmount", value);
                            } else if (j == 10) {
                                repaymentData.put("collectResults", value);
                            }
                        }
                    }

                    CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                    byKeyAndMerchantAndOrderNo.setDetailInfo(repaymentData.toString());
                    ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);

                    if (repaymentData.get("collectResults").equals("billing is successful")) {
                        order.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
                        order.setStatus(OrderStatusEnum.paid_update.getStatus());
                        ordersDao.updateByPrimaryKey(order);
                    } else {
                        order.setStatus(OrderStatusEnum.removed.getStatus());
                        order.setSyncStatus(OrderSyncStatusEnum.need_remove.getStatus());
                        ordersDao.updateByPrimaryKey(order);
                    }
                } catch (Exception e) {
                    LOGGER.error("== 检查还款订单异常 ==,orderNo:{}", order.getOrderNo(), e);
                }

            }
        });
    }

    @Override
    public void updatePaidOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 开始同步有更新的数据到催收系统 ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_pay_update.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== 开始同步有更新的数据到催收系统 没有还款订单==");
            return;
        }

        LOGGER.info("== 开始同步有更新的数据到催收系统 有还款==,size:{}", todayListBySyncStatusAndAgent.size());
        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                Any deserialize;
                if (agentAccount.getStage().contains("s")) {
                    deserialize = JsonIterator.deserialize(byKeyAndMerchantAndOrderNo.getDetailInfo());
                } else {
                    deserialize = JsonIterator.deserialize(order.getOrderInfo());
                }

                String paidAmount = deserialize.get("paidAmount").toString();
                ClRepaymentRequest request = new ClRepaymentRequest()
                        .setDeductAmount("0")
                        .setOrderBillNo(order.getCollectionNo())
                        .setPaidAmount(paidAmount)
                        .setPaidStatus(2)
                        .setPaidType(1)
                        .setRepayBizNo(IdUtils.genId() + "")
                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
                        .setTotalDeductAmount("0")
                        .setTotalPaidAmount(paidAmount)
                        .setTradeNo(order.getCollectionNo());

                HttpHeaders headers = new HttpHeaders();
                headers.set("Content-Type", "application/json;charset=utf-8");

                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl(), requestPush, String.class);
                String responseStr = responseEntity.getBody().toString();
                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl());
                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_success.getStatus());
                } else {
                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
                }
            } catch (Exception e) {
                LOGGER.error("=======  推送collection请求结果 error  ======", e);
                order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
            }
            ordersDao.updateByPrimaryKey(order);
        });

    }

    @Override
    public void updateRemovedOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("==  updateRemovedOrderToCollection 开始同步有更新的数据到催收系统 ==");
//        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_remove.getStatus());
//        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
//            LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 没有需要移除的订单==");
//            return;
//        }
//
//        LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 有数据需要移除==,size:{}", todayListBySyncStatusAndAgent.size());
//        todayListBySyncStatusAndAgent.forEach(order -> {
//            try {
//                CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
//                Any deserialize = JsonIterator.deserialize(byKeyAndMerchantAndOrderNo.getDetailInfo());
//                String paidAmount = new BigDecimal(deserialize.get("repayInfo").get("true_total_money").toString()).divide(new BigDecimal(100)).toString();
//                ClRepaymentRequest request = new ClRepaymentRequest()
//                        .setDeductAmount("0")
//                        .setOrderBillNo(order.getCollectionNo())
//                        .setPaidAmount(paidAmount)
//                        .setPaidStatus(2)
//                        .setPaidType(1)
//                        .setRepayBizNo(IdUtils.genId() + "")
//                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
//                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
//                        .setTotalDeductAmount("0")
//                        .setTotalPaidAmount(paidAmount)
//                        .setTradeNo(order.getCollectionNo());
//
//                HttpHeaders headers = new HttpHeaders();
//                headers.set("Content-Type", "application/json;charset=utf-8");
//
//                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
//                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl()_remove, requestPush, String.class);
//                String responseStr = responseEntity.getBody().toString();
//                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl()_remove);
//                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
//                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_success.getStatus());
//                } else {
//                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//                }
//            } catch (Exception e) {
//                LOGGER.error("=======  推送collection请求结果 error  ======", e);
//                order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//            }
//            ordersDao.updateByPrimaryKey(order);
//        });

    }

    @Override
    public void composeNote(CeCommentPushLogEntity ceCommentPushLogEntity) {

        ceCommentPushLogEntity.setStatus(1);
        commentPushLogDao.updateByPrimaryKey(ceCommentPushLogEntity);
    }


    /**
     * @param ceCommentPushLogEntity
     * @return 1 connected   1-7 willingness-to-repay
     * 1-11 willing to repay
     * 1-5 虚假个人信息
     * 2  no-answer
     * 3  empty-number / halt / shutdown
     * 4  reject / hang-up / pull-black
     */
    @Override
    public boolean sendNote(CeCommentPushLogEntity ceCommentPushLogEntity) {
        LOGGER.info("== 开始同步催记到甲方 ==");

        OkRupeeCollectionTagEnum currentTag = OkRupeeCollectionTagEnum.RNR_V2;

        for (OkRupeeCollectionTagEnum e : OkRupeeCollectionTagEnum.values()) {
            if (e.getType().equals(ceCommentPushLogEntity.getTargetType())) {
                currentTag = e;
            }
        }

        try {
            CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceCommentPushLogEntity.getMerchantCode());
            CeAgentAccountEntity account = agentAccountDao.getByAgentCode(ceCommentPushLogEntity.getAgentCode());
            CeOrdersEntity ceOrdersEntity = ordersDao.getOneByOrderNo(ceCommentPushLogEntity.getOriginNo());
            Any orderInfo = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
            CeOrdersDetailEntity baseInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(ceMerchantEntity.getMerchantCode(), "baseInfo", ceOrdersEntity.getOrderNo());
            Any baseInfoJson = JsonIterator.deserialize(baseInfo.getDetailInfo());
            Map<String, String> headers = getHeaders(account);

                HashMap<String, String> params = Maps.newHashMap();
//                String url = ceMerchantEntity.getApiDomain() + "/index.php?r=work-desk/nx-call&call_id=" + baseInfoJson.get("callId").toString() + "&tel=" + baseInfoJson.get("phone").toString() + "&loan_collection_order_id=" + orderInfo.get("id").toString() + "&loanOrder_id=" + orderInfo.get("orderNumber").toString() + "&contact_name=" + baseInfoJson.get("name").toString().replace(" ", "+") + "&relation=private";
//                String result = HttpUtil.getPage(url, params, headers);
            String cuishouUrl = ceMerchantEntity.getApiDomain() + "/index.php?r=work-desk/save-cuishou-log";
            String param = "name=" + baseInfoJson.get("name").toString() + "&phone=" + baseInfoJson.get("phone").toString() + "&relation=private&contact_type=0&user_order_id=" + orderInfo.get("id").toString();
            String result = HttpUtil.postFrom(cuishouUrl, headers, param);
            LOGGER.info("== OkRupee 开始同步催记到甲方 ==,res:{}", result);
            if ("0".equals(result)) {
                LOGGER.info("== 开始同步催记到甲方 success==");
                String detailUrl = ceMerchantEntity.getApiDomain() + "/index.php?r=work-desk/collection-detail&order_id=" + orderInfo.get("id").toString();
                String detailInfo = HttpUtil.getPage(detailUrl, params, headers);

                Document document = Jsoup.parse(detailInfo);
                Elements tables = document.select("table");
                Elements repaymentTrs = tables.get(tables.size() - 1).select("tr");
                String collectionId = "";
                Elements tds = repaymentTrs.get(1).select("td");
                for (int j = 0; j < tds.size(); j++) {
                    if (j == 8) {
                        List<Node> nodes = tds.get(j).childNodes();
                        for (int i = 0; i < nodes.size(); i++) {
                            if (!nodes.get(i).toString().trim().equals("")) {
                                collectionId = nodes.get(i).attributes().get("_bak_id");
                            }
                        }
                    }
                }
                LOGGER.info("== collectionID ==,id:{}", collectionId);
                String statusUrl = ceMerchantEntity.getApiDomain() + "/index.php?r=work-desk/save-feedback-status";
                RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                        .addFormDataPart("id", collectionId)
                        .addFormDataPart("val", currentTag.getState().toString())
                        .build();
                String statusResult = HttpUtil.postFormData(statusUrl, headers, body);
                if ("0".equals(JsonIterator.deserialize(statusResult).get("code").toString())) {
                    LOGGER.error("== 开始添加催记反馈到甲方 success==");
                } else {
                    LOGGER.error("== 开始添加催记反馈到甲方 error==");
                }

                return true;
            } else {
                LOGGER.error("== 开始同步催记到甲方 error==");
            }
        } catch (Exception e) {
            LOGGER.error("== 开始同步催记到甲方 异常==", e);
        }
        return false;
    }

    @Override
    public String updateRepaymentLink(String collectionNo, boolean isReduce) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = null;
        if (ceOrdersEntity.getMerchantCode().equals("okrupee")) {
            accountEntity = agentAccountDao.getByAgentCode("okrupeeadmin");
        } else if (ceOrdersEntity.getMerchantCode().equals("cashmart")) {
            accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        }
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());
        Any repaymentInfo = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
        Map<String, String> headers = getHeaders(accountEntity);

        String channelLink = ceMerchantEntity.getApiDomain() + "/index.php?r=order%2Frequest-repay";
        String result = HttpUtil.getPage(channelLink, Maps.newHashMap(), headers);


        Document document = Jsoup.parse(result);
        Elements repayTrs = document.select("select").select("option");
        if (repayTrs.size() == 0) {
            return "fail";
        }
        try {
            LOGGER.info("=== OkRupee还款方式 ===,channelLink:{},headers:{},size:{}", channelLink, JsonStream.serialize(headers), repayTrs.size());
        } catch (Exception e) {
            LOGGER.error("=== OkRupee还款方式 ===", e);
        }

        String channelID = repayTrs.get(0).attributes().get("value");
        LOGGER.info("=== OkRupee还款方式 ===,channelID:{}", channelID);
        if (ceOrdersEntity.getMerchantCode().equals("okrupee")) {
            for (int i = 0; i < repayTrs.size(); i++) {
                String s = repayTrs.get(i).childNodes().get(0).toString();
                LOGGER.info("=== OkRupee还款方式2 ===,s:{}", s);
                if (s.equals(apolloConfigUtil.getOkRupeeRepayChannel())) {
                    channelID = repayTrs.get(i).attributes().get("value");
                    break;
                }
            }

        } else if (ceOrdersEntity.getMerchantCode().equals("cashmart")) {
            for (int i = 0; i < repayTrs.size(); i++) {
                if (repayTrs.get(i).childNodes().get(0).toString().equals(apolloConfigUtil.getCashMartRepayChannel())) {
                    channelID = repayTrs.get(i).attributes().get("value");
                    break;
                }
            }
        }
        String repaymentLinkUrl = ceMerchantEntity.getApiDomain() + "/index.php?r=order%2Frequest-repay";
        RequestBody body = new MultipartBody.Builder().setType(MediaType.parse("multipart/form-data"))
                .addFormDataPart("order_no", ceOrdersEntity.getOrderNo())
                .addFormDataPart("platform_id", channelID)
                .addFormDataPart("isDelay", "0")
                .addFormDataPart("amount", repaymentInfo.get("remainingAmount").toString())
                .addFormDataPart("isNew", "1")
                .addFormDataPart("showLink", "1")
                .build();
        String linkResult = HttpUtil.postFormData(repaymentLinkUrl, headers, body);
        LOGGER.info("=== OkRupee还款链接 ===,linkResult:{}", linkResult);
        Any deserialize = JsonIterator.deserialize(linkResult);
        String link = "Get Link Err";
        if (deserialize.get("code").toInt() == 200) {
            link = deserialize.get("data").get("repayUrl").toString();
        }
        return link;
    }

    public static void main(String[] args) {
        String channelLink = "http://149.129.190.153/index.php?r=order%2Frequest-repay";
        Map<String, String> headers = new HashMap<>();
        headers.put("Cookie", "CS-SESSIONID=uqnogcbr216arv7r3gotdd9bff; _csrf=bfe55f4a507eefe20c9ec3d9600e02c615f074d2ab946adb32091b3c23527ae6a%3A2%3A%7Bi%3A0%3Bs%3A5%3A%22_csrf%22%3Bi%3A1%3Bs%3A32%3A%22uKaHelJvW9EMmz1jXSND-QkQusTWPwVG%22%3B%7D");
        headers.put("Content-Type", "application/json");
        String result = HttpUtil.getPage(channelLink, Maps.newHashMap(), headers);
        Document document = Jsoup.parse(result);
        Elements repayTrs = document.select("select").select("option");
        String channelID = repayTrs.get(0).attributes().get("value");
        for (int i = 0; i < repayTrs.size(); i++) {
            channelID = repayTrs.get(i).attributes().get("value");
        }

        System.err.println(11);

    }

    @Override
    public String updateExtensionRepaymentLink(String collectionNo, boolean isOpen) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = null;
        if (ceOrdersEntity.getMerchantCode().equals("okrupee")) {
            accountEntity = agentAccountDao.getByAgentCode("okrupeeadmin");
        } else if (ceOrdersEntity.getMerchantCode().equals("cashmart")) {
            accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        }
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());
        Any repaymentInfo = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
        Map<String, String> headers = getHeaders(accountEntity);

        String channelLink = ceMerchantEntity.getApiDomain() + "/index.php?r=order%2Frequest-repay";
        String result = HttpUtil.getPage(channelLink, Maps.newHashMap(), headers);
        Document document = Jsoup.parse(result);
        Elements repayTrs = document.select("select").select("option");
        if (repayTrs.size() == 0) {
            return "fail";
        }
        String channelID = repayTrs.get(0).attributes().get("value");
        if (ceOrdersEntity.getMerchantCode().equals("okrupee")) {
            for (int i = 0; i < repayTrs.size(); i++) {
                if (repayTrs.get(i).childNodes().get(0).toString().equals(apolloConfigUtil.getOkRupeeRepayChannel())) {
                    channelID = repayTrs.get(i).attributes().get("value");
                    break;
                }
            }

        } else if (ceOrdersEntity.getMerchantCode().equals("cashmart")) {
            for (int i = 0; i < repayTrs.size(); i++) {
                if (repayTrs.get(i).childNodes().get(0).toString().equals(apolloConfigUtil.getCashMartRepayChannel())) {
                    channelID = repayTrs.get(i).attributes().get("value");
                    break;
                }
            }
        }
        String totalLoanAmount = new BigDecimal(repaymentInfo.get("remainingAmount").toString()).multiply(new BigDecimal("0.4")).toString();
        String repaymentLinkUrl = ceMerchantEntity.getApiDomain() + "/index.php?r=order%2Frequest-repay";
        RequestBody body = new MultipartBody.Builder().setType(MediaType.parse("multipart/form-data"))
                .addFormDataPart("order_no", ceOrdersEntity.getOrderNo())
                .addFormDataPart("platform_id", channelID)
                .addFormDataPart("isDelay", "1")
                .addFormDataPart("amount", totalLoanAmount)
                .addFormDataPart("isNew", "1")
                .addFormDataPart("showLink", "1")
                .build();
        String linkResult = HttpUtil.postFormData(repaymentLinkUrl, headers, body);
        LOGGER.info("=== OkRupee展期链接 ===,linkResult:{}", linkResult);
        Any deserialize = JsonIterator.deserialize(linkResult);
        String link = "Get Link Err";
        if (deserialize.get("code").toInt() == 200) {
            link = deserialize.get("data").get("repayUrl").toString();
        }
        CeRepaymentLinkEntity entity = new CeRepaymentLinkEntity();
        entity.setMerchantCode(ceMerchantEntity.getMerchantCode());
        entity.setAgentCode(accountEntity.getAgentCode());
        entity.setCollectionNo(ceOrdersEntity.getCollectionNo());
        entity.setStatus(1);
        entity.setOtherInfo("");
        entity.setPaymentUrl(link);
        repaymentLinkDao.insert(entity);
        return link;
    }

    @Override
    public String addPaymentOrder(String orderNo, String fileName, String fileUrl, String utr, String remark, String amount) {
        LOGGER.info("== OkRupee补单 ==,orderNo:{},fileUrl:{},utr:{},remark:{},amount:{}", orderNo, fileUrl, utr, remark, amount);
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByOrderNo(orderNo);
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());
        CeAgentAccountEntity account = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        Any orderInfo = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
        String orderId = orderInfo.get("id").toString();
        Map<String, String> headers = getHeaders(account);

        LOGGER.info("== OkRupee补单 ==,agentCode:{}", account.getAgentCode());

        String addPaymentOrderUrl = ceMerchantEntity.getApiDomain() + "/index.php?r=order/add-replenishment-order&order_id=" + orderId;

        try {
            RequestBody imgBody = RequestBody.create(MediaType.parse("application/octet-stream"),
                    getFile(fileUrl));
            String imageName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1) + ".jpeg";

            RequestBody body = new MultipartBody.Builder().setType(MediaType.parse("multipart/form-data"))
                    .addFormDataPart("order_no", orderNo)
                    .addFormDataPart("order_id", orderId)
                    .addFormDataPart("utr", utr)
                    .addFormDataPart("amount", amount)
                    .addFormDataPart("img", imageName, imgBody)
                    .addFormDataPart("pay_time", DateUtil.getDate("yyyy-MM-dd") + "T" + DateUtil.getDate("HH:mm"))
                    .addFormDataPart("is_delay", remark.contains("Extension") ? "1" : "0")
                    .build();
            String addPaymentOrderResult = HttpUtil.postFormData(addPaymentOrderUrl, headers, body);
            LOGGER.info("== OkRupee补单 ==,result:{}", addPaymentOrderResult);
            Document pendingRes = Jsoup.parse(addPaymentOrderResult);
            Elements h4 = pendingRes.select("h4");
            String msg = h4.get(0).text().toString();
            LOGGER.info("== OkRupee补单 ==,msg:{}", msg);
            if (msg.equals("Success")) {//提交成功
                LOGGER.info("== OkRupee补单成功 ==,orderNo:{}", orderNo);
                return msg;
            } else {//重复提交
                LOGGER.info("== OkRupee补单失败 ==,orderNo:{}", orderNo);
                return msg;
            }
        } catch (Exception e) {
            return e.getMessage();
        }
    }


    @Override
    public String queryPaymentOrderResult(String orderNo, String utr) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByOrderNo(orderNo);
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());
        CeAgentAccountEntity account = agentAccountDao.getByAgentCode("okrupeeadmin");

        Map<String, String> headers = getHeaders(account);
        String queryPaymentOrderUrl = ceMerchantEntity.getApiDomain() + "/index.php?r=order/inside-fix-repay-list&start_time=" + DateUtil.getDate("yyyy-MM-dd") + "&end_time=" + DateUtil.getDate("yyyy-MM-dd") + "&orderNo=" + orderNo + "&utr=" + utr + "&response=&status=&source=&collection_user=&isDelay=";
        HashMap<String, String> params = Maps.newHashMap();
        String result = HttpUtil.getPage(queryPaymentOrderUrl, params, headers);
        Document document = Jsoup.parse(result);
        Elements repayTrs = document.select("table").select("tr");

        String queryResult = "";
        for (int i = 1; i < repayTrs.size(); i++) {
            Elements tds = repayTrs.get(i).select("td");

            for (int j = 0; j < tds.size(); j++) {
                if (tds.get(j).childNodes().size() <= 0) {
                    continue;
                }
                String value = tds.get(j).childNodes().get(0).toString();
                if (j == 10) {
                    queryResult = value;
                    break;
                }

            }
        }
        Any deserialize = JsonIterator.deserialize(queryResult);

        return deserialize.toString();
    }

    @Override
    public String checkOrdersPaid(String orderNo) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByOrderNo(orderNo);
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());
        CeAgentAccountEntity account = agentAccountDao.getByAgentCode("okrupeeadmin");

        Map<String, String> headers = getHeaders(account);
        String queryPaymentOrderUrl = ceMerchantEntity.getApiDomain() + "/index.php?r=order/inside-fix-repay-list&start_time=" + DateUtil.getDate("yyyy-MM-dd") + "&end_time=" + DateUtil.getDate("yyyy-MM-dd") + "&orderNo=" + orderNo + "&utr=&response=&status=&source=&collection_user=&isDelay=";
        HashMap<String, String> params = Maps.newHashMap();
        String result = HttpUtil.getPage(queryPaymentOrderUrl, params, headers);
        Document document = Jsoup.parse(result);
        Elements repayTrs = document.select("table").select("tr");

        String queryResult = "";
        for (int i = 1; i < repayTrs.size(); i++) {
            Elements tds = repayTrs.get(i).select("td");

            for (int j = 0; j < tds.size(); j++) {
                if (tds.get(j).childNodes().size() <= 0) {
                    continue;
                }
                String value = tds.get(j).childNodes().get(0).toString();
                if (j == 10) {
                    queryResult = value;
                    break;
                }

            }
        }
        Any deserialize = JsonIterator.deserialize(queryResult);

        return deserialize.get("data").get("message").toString();
    }

    public static void main11(String[] args) {
        String date = DateUtil.getDate("yyyy-MM-dd");
        String converseDate = DateUtil.getConverseDay(DateUtil.getDate("yyyy-MM-dd"), 6);

        String dayBeforeYesterday = DateUtil.getConverseYesterDate("");
        String hhh = DateUtil.getAfterSelectDay("yyyy-MM-dd", 1);
        LOGGER.info("====,dayBeforeYesterday:{},hhh:{}", converseDate, hhh);

    }


    private static File getNetUrlHttp(String path) {
        //对本地⽂件命名，path是http的完整路径，主要得到资源的名字
        String newUrl = path;
        newUrl = newUrl.split("[?]")[0];
        String[] bb = newUrl.split("/");
        //得到最后⼀个分隔符后的名字
        String fileName = bb[bb.length - 1];
        //保存到本地的路径
        String filePath = "e:\\audio\\" + fileName;
        File file = null;
        URL urlfile;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //判断⽂件的⽗级⽬录是否存在，不存在则创建
            file = new File(filePath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            try {
                //创建⽂件
                file.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
            //下载
            urlfile = new URL(newUrl);
            inputStream = urlfile.openStream();
            outputStream = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    public static File getFile(String url) throws Exception {
        //对本地文件命名
        String fileName = url.substring(url.lastIndexOf("/") + 1, url.length());
        File file = null;

        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            file = File.createTempFile("net_url", fileName);
            //下载
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return file;
    }
}
